package com.hurl.stock.biz.jcsj;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.ScrollableResults;

import com.hurl.stock.persistence.DmGpBO;
import com.hurl.stock.persistence.JcsjSinaSssjBO;
import com.hurl.stock.util.HibernateExecutor;
import com.hurl.stock.util.HibernateUtils;
import com.mysql.jdbc.StringUtils;

public class JcsjService {
	private static final Log log = LogFactory.getLog(JcsjService.class);
	
	private static JcsjSinaSssjBO getSinaSssjBO(SinaSssjLocation location, SinaSssjBuilder builder,int retry)throws JcsjException{
		if(retry<=0){
			return null;
		}
		try {
			return (JcsjSinaSssjBO)builder.build(location);
		} catch (JcsjException e) {
			e.printStackTrace();
			try {
				Thread.sleep(30000);
			} catch (InterruptedException e1) {
				throw new JcsjException(e1.getMessage(),e1);
			}
			return getSinaSssjBO(location,builder,retry-1);
		}
	}
	public static void searchSinaSssj() throws JcsjException{
		
		HibernateExecutor exec = HibernateUtils.createExecutor();
		exec.beginTransaction();
		
		ScrollableResults it = exec.createCriteria(DmGpBO.class).scroll();
		
		SinaSssjBuilder builder = new SinaSssjBuilder();
		SinaSssjLocation location = new SinaSssjLocation();
		JcsjSinaSssjBO sinaSssjBO = null;
		DmGpBO gpBO = null;
		int size = 0;
		while(it.next()){
			sinaSssjBO  = null;
			gpBO = null;
			location.setGpdm(null);
			location.setPrefix(null);
			
			gpBO = (DmGpBO)it.get(0);
			String gpdm = gpBO.getGpDm();
			String gplx = gpBO.getDmGplxBO()==null?"":gpBO.getDmGplxBO().getGplxDm();
			String prefix = null;
			if(StringUtils.startsWithIgnoreCase(gplx,"sh")){
				prefix = "sh";
			}else if(StringUtils.startsWithIgnoreCase(gplx, "sz")){
				prefix = "sz";
			}
			if(gpdm!=null && prefix!=null){
				location.setGpdm(gpdm);
				location.setPrefix(prefix);
				sinaSssjBO = getSinaSssjBO(location,builder,10);
				if(sinaSssjBO==null){
					log.warn("找不到股票数据，插入一个空BO（请求地址："+location.getURI()+"）");
					sinaSssjBO = new JcsjSinaSssjBO();
					sinaSssjBO.setGpDm(gpdm);
				}

				log.debug("save BO: "+sinaSssjBO);
				exec.save(sinaSssjBO);
				size++;
				
				exec.evict(gpBO);
				if(size%50 ==0){
					exec.flush();
				}
			}
		}
		exec.commit();
	}
	public static void clearSinaSssj(){
		HibernateExecutor exec = HibernateUtils.createExecutor();
		exec.beginTransaction();
		exec.updateHQL("DELETE FROM "+JcsjSinaSssjBO.class.getName(), null);
		exec.commit();

	}
}
